#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日志装饰器
用于自动记录用户操作和系统事件
"""

import functools
import logging
from typing import Callable, Any, Dict, Optional
from datetime import datetime

try:
    from .logger_manager import get_system_logger, OperationType, LogLevel
except ImportError:
    try:
        from src.utils.logger_manager import get_system_logger, OperationType, LogLevel
    except ImportError:
        get_system_logger = None
        OperationType = None
        LogLevel = None

logger = logging.getLogger(__name__)

def log_user_operation(operation_type: str, operation_desc: str = "", 
                      log_level: LogLevel = LogLevel.INFO):
    """
    用户操作日志装饰器
    
    Args:
        operation_type: 操作类型
        operation_desc: 操作描述
        log_level: 日志级别
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 获取系统日志管理器
            system_logger = get_system_logger() if get_system_logger else None
            
            # 执行原函数
            try:
                result = func(*args, **kwargs)
                
                # 记录成功日志
                if system_logger:
                    # 构建操作内容
                    operation_content = operation_desc
                    if not operation_content:
                        operation_content = f"执行{func.__name__}函数"
                    
                    # 构建详细信息
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "args_count": len(args),
                        "kwargs_count": len(kwargs),
                        "success": True,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    system_logger.log_user_operation(
                        operation_type=operation_type,
                        operation_content=operation_content,
                        details=details,
                        log_level=log_level
                    )
                
                return result
                
            except Exception as e:
                # 记录失败日志
                if system_logger:
                    operation_content = f"{operation_desc}失败: {str(e)}" if operation_desc else f"执行{func.__name__}函数失败: {str(e)}"
                    
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "args_count": len(args),
                        "kwargs_count": len(kwargs),
                        "success": False,
                        "error": str(e),
                        "error_type": type(e).__name__,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    system_logger.log_user_operation(
                        operation_type=operation_type,
                        operation_content=operation_content,
                        details=details,
                        log_level=LogLevel.ERROR
                    )
                
                # 重新抛出异常
                raise
        
        return wrapper
    return decorator

def log_data_reception(data_type: str, source: str = ""):
    """
    数据接收日志装饰器
    
    Args:
        data_type: 数据类型
        source: 数据来源
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 获取系统日志管理器
            system_logger = get_system_logger() if get_system_logger else None
            
            # 执行原函数
            try:
                result = func(*args, **kwargs)
                
                # 记录数据接收日志
                if system_logger:
                    # 构建操作内容
                    operation_content = f"成功接收{data_type}"
                    
                    # 构建详细信息
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "data_type": data_type,
                        "source": source,
                        "success": True,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    # 尝试从参数中提取数据内容
                    data_content = ""
                    if args and len(args) > 0:
                        if isinstance(args[0], str):
                            data_content = args[0][:100]  # 限制长度
                        elif hasattr(args[0], '__str__'):
                            data_content = str(args[0])[:100]
                    
                    system_logger.log_data_reception(
                        data_type=data_type,
                        data_content=data_content,
                        source=source,
                        details=details
                    )
                
                return result
                
            except Exception as e:
                # 记录失败日志
                if system_logger:
                    operation_content = f"接收{data_type}失败: {str(e)}"
                    
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "data_type": data_type,
                        "source": source,
                        "success": False,
                        "error": str(e),
                        "error_type": type(e).__name__,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    system_logger.log_data_reception(
                        data_type=data_type,
                        data_content=f"接收失败: {str(e)}",
                        source=source,
                        details=details
                    )
                
                # 重新抛出异常
                raise
        
        return wrapper
    return decorator

def log_system_event(event_type: str, event_desc: str = "", 
                    log_level: LogLevel = LogLevel.INFO):
    """
    系统事件日志装饰器
    
    Args:
        event_type: 事件类型
        event_desc: 事件描述
        log_level: 日志级别
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 获取系统日志管理器
            system_logger = get_system_logger() if get_system_logger else None
            
            # 执行原函数
            try:
                result = func(*args, **kwargs)
                
                # 记录成功日志
                if system_logger:
                    # 构建操作内容
                    operation_content = event_desc
                    if not operation_content:
                        operation_content = f"执行{func.__name__}系统事件"
                    
                    # 构建详细信息
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "args_count": len(args),
                        "kwargs_count": len(kwargs),
                        "success": True,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    system_logger.log_system_event(
                        event_type=event_type,
                        event_content=operation_content,
                        log_level=log_level,
                        details=details
                    )
                
                return result
                
            except Exception as e:
                # 记录失败日志
                if system_logger:
                    operation_content = f"{event_desc}失败: {str(e)}" if event_desc else f"执行{func.__name__}系统事件失败: {str(e)}"
                    
                    details = {
                        "function_name": func.__name__,
                        "module": func.__module__,
                        "args_count": len(args),
                        "kwargs_count": len(kwargs),
                        "success": False,
                        "error": str(e),
                        "error_type": type(e).__name__,
                        "timestamp": datetime.now().isoformat()
                    }
                    
                    system_logger.log_system_event(
                        event_type=event_type,
                        event_content=operation_content,
                        log_level=LogLevel.ERROR,
                        details=details
                    )
                
                # 重新抛出异常
                raise
        
        return wrapper
    return decorator

def log_communication_event(event_type: str, event_desc: str = ""):
    """
    通信事件日志装饰器
    
    Args:
        event_type: 事件类型
        event_desc: 事件描述
    """
    def decorator(func: Callable) -> Callable:
        @functools.wraps(func)
        def wrapper(*args, **kwargs):
            # 获取系统日志管理器
            system_logger = get_system_logger() if get_system_logger else None
            
            # 执行原函数
            try:
                result = func(*args, **kwargs)
                
                # 记录成功日志
                if system_logger:
                    # 构建操作内容
                    operation_content = event_desc
                    if not operation_content:
                        operation_content = f"执行{func.__name__}通信事件"
                    
                    # 构建连接信息
                    connection_info = {}
                    if args and len(args) > 0:
                        if hasattr(args[0], 'host'):
                            connection_info['host'] = args[0].host
                        if hasattr(args[0], 'port'):
                            connection_info['port'] = args[0].port
                        if hasattr(args[0], 'serial_port'):
                            connection_info['serial_port'] = args[0].serial_port
                    
                    system_logger.log_communication_event(
                        event_type=event_type,
                        event_content=operation_content,
                        connection_info=connection_info,
                        success=True
                    )
                
                return result
                
            except Exception as e:
                # 记录失败日志
                if system_logger:
                    operation_content = f"{event_desc}失败: {str(e)}" if event_desc else f"执行{func.__name__}通信事件失败: {str(e)}"
                    
                    # 构建连接信息
                    connection_info = {}
                    if args and len(args) > 0:
                        if hasattr(args[0], 'host'):
                            connection_info['host'] = args[0].host
                        if hasattr(args[0], 'port'):
                            connection_info['port'] = args[0].port
                        if hasattr(args[0], 'serial_port'):
                            connection_info['serial_port'] = args[0].serial_port
                    
                    system_logger.log_communication_event(
                        event_type=event_type,
                        event_content=operation_content,
                        connection_info=connection_info,
                        success=False
                    )
                
                # 重新抛出异常
                raise
        
        return wrapper
    return decorator

# 预定义的常用操作类型装饰器
def log_login(func: Callable) -> Callable:
    """登录操作日志装饰器"""
    return log_user_operation(OperationType.USER_LOGIN.value, "用户登录")(func)

def log_logout(func: Callable) -> Callable:
    """登出操作日志装饰器"""
    return log_user_operation(OperationType.USER_LOGOUT.value, "用户登出")(func)

def log_sample_operation(operation: str):
    """样本操作日志装饰器"""
    def decorator(func: Callable) -> Callable:
        return log_user_operation(operation, f"样本{operation}")(func)
    return decorator

def log_system_config(func: Callable) -> Callable:
    """系统配置操作日志装饰器"""
    return log_user_operation(OperationType.SYSTEM_CONFIG_UPDATE.value, "更新系统配置")(func)

def log_backup_operation(func: Callable) -> Callable:
    """备份操作日志装饰器"""
    return log_system_event(OperationType.SYSTEM_BACKUP.value, "系统备份")(func)

def log_communication_connect(func: Callable) -> Callable:
    """通信连接日志装饰器"""
    return log_communication_event(OperationType.COMMUNICATION_CONNECT.value, "建立通信连接")(func)

def log_communication_disconnect(func: Callable) -> Callable:
    """通信断开日志装饰器"""
    return log_communication_event(OperationType.COMMUNICATION_DISCONNECT.value, "断开通信连接")(func)

def log_data_receive_sample(func: Callable) -> Callable:
    """接收样本数据日志装饰器"""
    return log_data_reception("样本数据", "设备")(func)

def log_data_receive_result(func: Callable) -> Callable:
    """接收检测结果日志装饰器"""
    return log_data_reception("检测结果", "设备")(func) 